package com.example.service.admin;

import com.example.entity.DTO.StudentDetailDTO;
import com.example.entity.Major;
import com.example.entity.Student;
import com.example.exception.CustomException;
import com.example.mapper.StudentMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class StudentService {
    @Resource
    private StudentMapper studentMapper;

    public List<StudentDetailDTO> selectAllStudent(String studentName, String className, String majorName) {
        return studentMapper.selectAllStudentByNameAndClassNameAndMajorName(studentName, className, majorName);
    }

    public void addStudent(Student student) {
        String username = student.getUsername();
        Student dbStudent = studentMapper.selectByUsername(username);
        if(dbStudent != null) {
            throw new CustomException("500", "学号已存在!");
        }
        student.setRole("STU");
        student.setLastLoginTime(LocalDate.now());
        studentMapper.insert(student);
    }

    public Student selectStudent(String username) {
        return studentMapper.selectStudentByUsername(username);
    }

    public void updateStudent(Student student) {
        Integer id = student.getId();
        Student dbStudent = studentMapper.selectById(id);
        if(dbStudent == null) {
            throw new CustomException("500", "学生ID不存在!");
        }
        String dbUsername = dbStudent.getUsername();
        String username = student.getUsername();
        dbStudent = studentMapper.selectStudentByUsername(username);
        if(dbStudent != null && !dbUsername.equals(username)) {
            throw new CustomException("500", "学生学号已存在!");
        }
        student.setRole("STU");
        student.setLastLoginTime(LocalDate.now());
        studentMapper.AdminUpdateById(student);
    }

    public void deleteStudent(Integer id) {
        studentMapper.deleteById(id);
    }
}
